<template>
  <div>
    <div class="app-container">
      <!-- 使用esheader组件 -->
      <es-header title="购物车案例"></es-header>
      <es-goods v-for="item in goodslist" :key="item.id" :id="item.id"  :checked="item.goods_state" :count="item.goods_count" :price="item.goods_price"
      :title="item.goods_name" :thumb="item.goods_img" @stateChange="onGoodsStateChange" @countChange="onCountChange"></es-goods>
      <es-footer @fullChange="onFullStateChange" :amount="amount" :total="total"> </es-footer>

    </div>
  </div>
</template>

<script>
import EsHeader from "./components/es-header/Es-Header.vue";
import EsFooter from './components/es-footer/Es-Footer.vue';
import EsGoods from './components/es-goods/EsGoods.vue'
export default {
  name: "MyApp",
  components: {
    EsHeader,
    EsFooter,
    EsGoods
  },
  data() {
    return {
      goodslist: [],
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    async getGoodsList() {
        const {data:res}=await this.$http.get('/api/cart')
        if(res.status!==200) return alert('数据请求失败')
        this.goodslist=res.list
    },
    // 获得全选按钮的状态
    onFullStateChange(e){
      this.goodslist.forEach(x=>{
        x.goods_state=e
      })
    },
    // 获得每一个单选按钮的状态
    onGoodsStateChange(e){
      const findResult=this.goodslist.find(x=>x.id==e.id)
      if(findResult){
        findResult.goods_state=e.value
      }
    },
  onCountChange(e){
    this.goodslist.find(x=>x.id==e.id).goods_count=e.value
   
  }
  },
  computed:{
    amount(){
      // 用于计算总数
      let a=0;
      // 寻找状态为勾选的项
      this.goodslist.filter(x=>x.goods_state).forEach(x=>{
        a+=x.goods_price*x.goods_count
      });
      return a
    },
    total(){
      let b=0;
      // 寻找状态为勾选的项
      this.goodslist.filter(x=>x.goods_state).forEach(x=>{
        b+=x.goods_count
      });
      return b
    }
  }
};
</script>

<style lang="less" scoped>
.app-container {
  margin-top: 45px;
}
</style>